﻿if (typeof (dxrApp) === 'undefined')
    dxrApp = angular.module('dxr.controls', []);

dxrApp.directive('dxrPager', function () {
    return {
        scope: {
            "option": '='
        },
        restrict: 'AE',
        replace: true,
        templateUrl: "/content/directives/pager.html",
        link: function ($scope, elem, attrs) {

            var defaultPaging = {
                index: 1,
                //count: 1,
                size: 10,
            };
            $scope.currentIndex = 1;
            $scope.showLast = true;

            var _paging;

            $scope.changeIndex = function (index) {
                if (index < 1)
                    index = 1;
                if (!$dxr.isNullOrEmpty(_paging.count) && index > $scope.maxPage)
                    index = $scope.maxPage;

                if ($scope.currentIndex == index)
                    return;

                $scope.currentIndex = index;

                $scope.option.pageChanged($scope.currentIndex);
            };

            $scope.option.setPaging = function (paging) {

                paging = $.extend(true, defaultPaging, paging);
                _paging = paging;
                $scope.maxPage = 0;
                $scope.pages = [];
                var pageLength = 1;

                if ($dxr.isNullOrEmpty(paging.count)) {
                    pageLength = 1;
                    $scope.maxPage = 10000;
                    $scope.showLast = false;
                }
                else {
                    $scope.maxPage = Math.ceil(paging.count / paging.size);
                    pageLength = Math.min(9, $scope.maxPage);
                    $scope.showLast = true;
                }

                for (var i = Math.max(Math.min(paging.index + 5, $scope.maxPage + 1) - pageLength, 1) ; i < paging.index; i++) {
                    var item = {
                        class: "",
                        display: i,
                        value: i,
                    }

                    $scope.pages.push(item);
                }

                $scope.pages.push({
                    class: "active",
                    display: paging.index,
                    value: paging.index,
                });

                for (var i = 0; i < pageLength - $scope.pages.length ; i++) {
                    var item = {
                        class: "",
                        display: paging.index + 1 + i,
                        value: paging.index + 1 + i,
                    }

                    $scope.pages.push(item);
                }

                $scope.currentIndex = paging.index;
            };
        },
    };
});